package com.ysd.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ysd.entity.User;
import com.ysd.service.UserService;
import com.ysd.util.Result;



@RestController
public class UserController {
		
	@Autowired
	private UserService usService;
	
	@Resource
		private SimpleDateFormat dateFormat;
	
	@RequestMapping("getUser")
	public Object getUsers(User u) {
		u.setPage((u.getPage()-1)*u.getLimit());
		List<User>	list=usService.findUsers(u);

		if (list!=null) {
			int	count=usService.findCount(u);
			return Result.toClient("0", "查询成功", count, list);
		} else {
			return Result.toClient("1","查询失败");
		}
	}

	
	@RequestMapping("getName")
	public Object getName(User u) {
		return	usService.findByUsers(u);
		
	}
	
	@RequestMapping("addUsers")
	public Object addUsers(User u) {
		User	user=usService.findByUsers(u);
		if(user==null) {
			int	n=usService.insertUsers(u);
			if(n>0) {
				return Result.toClient("0", "添加成功");
			} else {
				return Result.toClient("1", "添加失败");
			}
		} else {
			return Result.toClient("1", "用户名已存在");
		}
		
	}
	
	@RequestMapping("updateUsers")
	public Object updateUsers(User u) {
		int	n=usService.updateUsers(u);
		if (n>0) {
			return Result.toClient("0", "修改成功");
		} else {
			return Result.toClient("1", "修改失败");
		}
		
	}
	
	@RequestMapping("updatePSW")
	public Object updatePSW(User u) {
		int	n=usService.updatePSW(u);
		if (n>0) {
			return Result.toClient("0", "重置成功");
		} else {
			return Result.toClient("1", "重置失败");
		}
		
	}
	
	//锁定
		@RequestMapping("lockoutUser")
		public Object lockoutUser(User u,String LockTime) {
			LockTime=dateFormat.format(new Date());
			User user=usService.findUsersByIdAndIsLockout(u);
			if (user==null) {
				u.setLockTime(LockTime);
				int n=usService.suoDingUser(u);
				if (n>0) {
					return Result.toClient("0", "锁定成功");
				}else {
					return Result.toClient("1", "锁定失败");
				}
			}
			return Result.toClient("0", "该用户已被锁定无法再次锁定");
		}
		//解锁
		@RequestMapping("unlockingUser")
		public Object unlockingUser(User u,String LockTime) {
			User user=usService.findUsersByIdAndIsLockout(u);
			if (user==null) {
				int n=usService.jieSuoUser(u);
				if (n>0) {
					u.setLockTime(null);
					return Result.toClient("0", "解锁成功");
				}else {
					return Result.toClient("1", "解锁失败");	
				}
			}
			return Result.toClient("1", "解锁状态下无法再次解锁");
		}
}
